package middleware

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/juju/errors"
	"go.mongodb.org/mongo-driver/bson"
	"qihuang/db/mongo"
	"qihuang/loger"
	"time"
)

type AccessLog struct {
}

type AccessLogParams struct {
	Ip        string `json:"ip"`
	Timestamp int64  `json:"timestamp"`
	Path      string `json:"path"`
	Date      string `json:"date"`
}

func (this *AccessLog) Add(log *AccessLogParams) error {
	mg, err := mongo.Default()
	if err != nil {
		return err
	}
	mongoconn := mg.GetConn()
	collection := mongoconn.Database("myblog").Collection("access_log")
	ctx, _ := context.WithTimeout(context.Background(), 5*time.Second)
	access_log, err := bson.Marshal(log)
	if err != nil {
		return err
	}
	_, err = collection.InsertOne(ctx, access_log)
	return err
}

func AddAccessLog() gin.HandlerFunc {
	return func(c *gin.Context) {
		go func() {
			var accessLogServ AccessLog
			params := &AccessLogParams{}
			params.Ip = c.ClientIP()
			params.Timestamp = time.Now().Unix()
			params.Path = c.Request.Method + "|" + c.Request.URL.Path
			params.Date = time.Now().Format("2006-01-02")
			err := accessLogServ.Add(params)
			if err != nil {
				loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
			}
		}()
		c.Next()
	}

}
